//
//  LoginViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/4/24.
//

#import "LoginViewController.h"
#import "UIView_extension.h"
#import "PasswordLoginViewController.h"
#import "RegisterViewController.h"
#import "WebShowViewController.h"
#import "AppService.h"

@interface LoginViewController (){
    BOOL    hasLogin;
}
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (strong, nonatomic) NSTimer     *timer;
@property (assign, nonatomic) NSInteger   count;
@end

@implementation LoginViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    [self initView];
    hasLogin = NO;
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (hasLogin) {
        [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = YES;

    }
    self.codeTextField.text = @"";
}

- (IBAction)backPress {
    [self goBackAction];
}

- (IBAction)changePasswordLoginPress {
    PasswordLoginViewController *viewCon = [[PasswordLoginViewController alloc] initWithNibName:@"PasswordLoginViewController" bundle:nil];
    [self.navigationController pushViewController:viewCon animated:YES];
}

- (IBAction)loginPress {
    if (self.phoneTextField.text.length != 11 && ![self.phoneTextField.text isEqualToString:@"admin"]) {
        [self showHUDAlert:@"请输入手机号"];
        return;
    }
    if (self.codeTextField.text.length == 0) {
        [self showHUDAlert:@"请输入验证码"];
        return;
    }
    [self loadingHUDAlert];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.phoneTextField.text forKey:@"mobile"];
    [dic setObject:self.codeTextField.text forKey:@"verifyCode"];
    [[ServiceRequest sharedService] POSTJSON:@"user" parameters:dic success:^(id responseObject) {
        [self hideHudAlert];
        if ([self.phoneTextField.text isEqualToString:@"15050137225"]) {
            [DEFAULTS setBool:YES forKey:@"TASKDATALOAD"];
        } else {
            [DEFAULTS setBool:NO forKey:@"TASKDATALOAD"];
        }
        
        UserInfo *user = [UserInfo mj_objectWithKeyValues:responseObject];
        [DEFAULTS setObject:user.platformId forKey:USERID];
        [DEFAULTS synchronize];
        [UserManger setUser:user];
        
        [[AppService sharedAppService] login:self.phoneTextField.text password:WFChatPassword success:^(NSString *userId, NSString *token, BOOL newUser) {
            [[NSUserDefaults standardUserDefaults] setObject:self.phoneTextField.text forKey:@"savedName"];
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"savedToken"];
            [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"savedUserId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[WFCCNetworkService sharedInstance] connect:userId token:token];
            [[ServiceRequest sharedService] PUTJSON:[NSString stringWithFormat:@"user/%@", user.platformId] parameters:@{@"pushUserId":userId} success:^(id responseObject) {
            } failure:^(NSString *error, NSInteger code) {
            }];
        } error:^(int errCode, NSString *message) {
            NSLog(@"login error with code %d, message %@", errCode, message);
        }];
        
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    } failure:^(NSString *error, NSInteger code) {
        [self showHUDAlert:error];
    }];
}

- (IBAction)registerPress {
    RegisterViewController *viewCon = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:viewCon animated:YES];
}


- (IBAction)codePress {
    [self.codeBtn setTitle:@"正在获取" forState:UIControlStateNormal];
    self.codeBtn.userInteractionEnabled = NO;
    [[ServiceRequest sharedService] GET:[NSString stringWithFormat:@"user/%@/sms", self.phoneTextField.text] parameters:nil success:^(id responseObject) {
        self.count = 60;
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:self
                                               selector:@selector(updateTime)
                                               userInfo:nil
                                                repeats:YES];
    } failure:^(NSString *error, NSInteger code) {
        [self showHUDAlert:error];
        [self.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = YES;

    }];
    
}

#pragma mark 更新时间
-(void)updateTime {
    self.count--;
    if (self.count > 0) {
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%lds",(long)self.count] forState:UIControlStateNormal];
        return;
    } else {
        self.codeBtn.userInteractionEnabled = YES;
        [self.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (IBAction)fuwuPress {
    WebShowViewController *viewCon = [[WebShowViewController alloc] initWithNibName:@"WebShowViewController" bundle:nil];
    viewCon.urlStr = AgreementUrl;
    viewCon.titleStr = @"用户协议";
    [self.navigationController pushViewController:viewCon animated:YES];
}

- (IBAction)yinsiPress {
    WebShowViewController *viewCon = [[WebShowViewController alloc] initWithNibName:@"WebShowViewController" bundle:nil];
    viewCon.urlStr = PrivacyUrl;
    viewCon.titleStr = @"隐私协议";
    [self.navigationController pushViewController:viewCon animated:YES];
}

- (void)initView {
    [self.backBtn setFrame:CGRectMake(0, IS_iPhoneX_Top, 44, 44)];
    [self.changeBtn setFrame:CGRectMake(SCREEN_WIDTH_DEVICE - 70, IS_iPhoneX_Top, 60, 44)];
    [self.titleLabel setFrame:CGRectMake((SCREEN_WIDTH_DEVICE - 100)/2.0, IS_iPhoneX_Top, 100, NavBarHeight)];
    [self.topView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 98)];
    [self.contentView setFrame:CGRectMake(0, CGRectGetMaxY(self.topView.frame) + 22, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - CGRectGetMaxY(self.topView.frame) - 22 - TabbarHeight - IS_iPhoneX_Bottom)];
    [self.contentView addRoundedCorners:UIRectCornerTopLeft | UIRectCornerTopRight withRadii:CGSizeMake(15,15)];
    [self.scrollView setAlwaysBounceVertical:YES];
    [self.scrollView setContentSize:CGSizeMake(SCREEN_WIDTH_DEVICE, 424
                                               )];
    [self.loginBtn setFrame:CGRectMake(30, 252, SCREEN_WIDTH_DEVICE - 60, 50)];
    [self.loginBtn setBackgroundColor:ThemeColor];
    addShadowToView(self.loginBtn, 0.3, 8, 25);
    
    [self.changeBtn setFrame:CGRectMake(30, CGRectGetMaxY(self.loginBtn.frame) + 12, SCREEN_WIDTH_DEVICE - 60, 50)];
    [self.changeBtn setBackgroundColor:ActionColor];
    addShadowToView(self.changeBtn, 0.3, 8, 25);
    
    [self.registerBtn setFrame:CGRectMake(30, CGRectGetMaxY(self.changeBtn.frame) + 12, SCREEN_WIDTH_DEVICE - 60, 50)];
    [self.registerBtn setBackgroundColor:PassColor];
    addShadowToView(self.registerBtn, 0.3, 8, 25);
    
    self.codeBtn.layer.masksToBounds = YES;
    self.codeBtn.layer.cornerRadius = 14.0f;
    self.codeBtn.layer.borderWidth = 0.5f;
    self.codeBtn.layer.borderColor = ThemeColor.CGColor;
}

@end
